package com.live.dengdengtv.net;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.live.dengdengtv.view.DialogWaiting;


public abstract class WeakAsyncTask<Params, Progress, Result, WeakTarget>
		extends AsyncTask<Params, Progress, Result> {
	protected WeakReference<WeakTarget> mTarget;
	protected Params[] params;
	protected DialogWaiting progressDialog;

	public WeakAsyncTask(WeakTarget target) {
		mTarget = new WeakReference<WeakTarget>(target);
	}

	/** {@inheritDoc} */
	@Override
	protected final void onPreExecute() {
		final WeakTarget target = mTarget.get();
		if (target != null && !isFinishing()) {
			progressDialog = DialogWaiting.show((Context) target);
			this.onPreExecute(target);
		}
	}

	/** {@inheritDoc} */
	@Override
	protected final Result doInBackground(Params... params) {
		this.params = params;
		final WeakTarget target = mTarget.get();
		if (target != null && !isFinishing()) {
			return this.doInBackground(target, params);
		} else {
			return null;
		}
	}

	/** {@inheritDoc} */
	@Override
	protected final void onPostExecute(Result result) {
		if (!isFinishing()) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			final WeakTarget target = mTarget.get();
			if (target != null) {
				this.onPostExecute(target, result);
			}
		}
	}

	@Override
	protected void onProgressUpdate(Progress... progress) {
		final WeakTarget target = mTarget.get();
		if (target != null && !isFinishing()) {
			this.onProgressUpdate(target, progress);
		}
	}

	protected void onPreExecute(WeakTarget target) {
		// No default action
	}

	protected abstract Result doInBackground(final WeakTarget target,
			Params... params);

	protected void onPostExecute(WeakTarget target, Result result) {
		// No default action
	}

	protected void onProgressUpdate(WeakTarget target, Progress... progress) {
		// No default action
	}

	protected WeakTarget getTarget() {
		return mTarget.get();
	}

	private boolean isFinishing() {
		Activity act = (Activity) mTarget.get();
		return act.isFinishing();
	}
}
